﻿using System;
using System.Collections.Generic;
using System.Data.Objects.DataClasses;
using System.Linq;
using System.Web.Mvc;
using Citi.Scheduler.WebUi.Models;
using Citi.Scheduler.Domain;

namespace Citi.Scheduler.WebUi.Controllers
{
    public class ScheduleController : ControllerBase<ScheduleModel, Schedule>
    {
        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public ActionResult Form(int? id)
        {
            //FillViewBag();
            //return PartialView();
            return ActionBase(id, true);
        }

        public void FillViewBag(Enums.Periodicity? periodicity = null)
        {
            var periodicities = new Enums.Periodicity().ToSelectList(true, true);
            if (periodicity.HasValue)
                periodicities.First(x => x.Text == periodicity.Value.GetDescription()).Selected = true;

            ViewBag.Periodicities = periodicities;

            var repeatEvery = new List<SelectListItem>();

            for (var i = 1; i < 31; i++)
                repeatEvery.Add(new SelectListItem { Text = i.ToString(), Value = i.ToString() });

            ViewBag.RepeatEvery = repeatEvery;
        }

        public int Save(ScheduleModel model, string repeat)
        {
            //base.ActionBase(model);

            //var repeats = model.Periodicity == Enums.Periodicity.Weekly
            //                     ? repeat.Split(',').Select(x => new RepeatType { ScheduleId = idSchedule, Weekday = (short)Enum.Parse(typeof(DayOfWeek), x) }).ToList()
            //                     : new List<RepeatType> { new RepeatType { ScheduleId = idSchedule, MonthType = (short)(repeat == "WeekDay" ? 1 : 0) } };

            //repeats.ForEach(x => x.Save(x));

            //if (model.Id == 0)
            //{
            model.Id = 0;
            var dominioCriar = model.CreateDomain();

            switch (model.Periodicity)
            {
                case Enums.Periodicity.Monthly:
                    dominioCriar.RepeatTypes = new EntityCollection<RepeatType> { new RepeatType { MonthType = (short)(repeat == "DayWeek" ? MonthType.DayOfWeek : MonthType.DayOfMonth) } };
                    break;
                case Enums.Periodicity.Weekly:
                    var repeats = repeat.Split(',').Select(x => new RepeatType { Weekday = (short)((DayOfWeek)Enum.Parse(typeof(DayOfWeek), x)) }).ToList();
                    dominioCriar.RepeatTypes = new EntityCollection<RepeatType>();
                    repeats.ForEach(x => dominioCriar.RepeatTypes.Add(x));
                    break;
            }

            dominioCriar.Save(dominioCriar);
            Model = model.CreateModel(dominioCriar);
            //}
            //else
            //{
            //    SaveEdition(model, true);
            //    Model = model;
            //}

            return Model.Id;
        }
    }
}
